package com.controller.config.redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

//定时器
@EnableScheduling
@Component
public class TestSenderController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //向redis消息队列 通道 发布消息  并通过websocket分散在各个客户端
    @Scheduled(fixedRate = 5000)
    public void sendMessage() {
        LinkedBlockingQueue link1 = new LinkedBlockingQueue();
        LinkedBlockingQueue link2 = new LinkedBlockingQueue();

        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            link1.add("{\"type\":\"" + random.nextInt(4) + "\",\"moeny\":\"" + random.nextInt(99999) + "\"}");
        }
        for (int i = 0; i < 10; i++) {
            link2.add("{\"type\":\"" + random.nextInt(4) + "\",\"moeny\":\"" + random.nextInt(99999) + "\"}");
        }
        Map map = new HashMap();
        map.put("link1", link1);
        map.put("link2", link2);

        stringRedisTemplate.convertAndSend("data", JSON.toJSONString(map));
         int flag=0;
        for (int i = 0; i < link1.size(); i++) {
            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //把队列一的数据转map
            Map map1 = JSONObject.parseObject(link1.poll().toString(), Map.class);
            for (int j = 0; j < link2.size(); j++) {
                Map map2 = JSONObject.parseObject(link2.poll().toString(), Map.class);
                //两个队列的某一个type相同  计算价格
                if (map1.get("type").equals(map2.get("type"))) {
                    //标识有没有交易成功过
                    flag+=1;
                    int moeny = Integer.parseInt(map1.get("moeny")+"") - Integer.parseInt(map2.get("moeny")+"");

                    stringRedisTemplate.convertAndSend("moeny",  moeny+"");
                }
            }

        }
            if(flag==0){
                stringRedisTemplate.convertAndSend("end", "<a style='color:red'>本次交易完毕,本次模拟无交易</a>");

            }else{
                stringRedisTemplate.convertAndSend("end", "<a style='color:red'>本次交易完毕。</a>");
            }

    }
}